// import { Action, createReducer, on } from "@ngrx/store";
// import { v4 as uuidv4 } from "uuid";
// import { addTodo, delTodo } from "../actions/todo.actions";

// export const todoFeatureKey = "todo";

// export interface Todo {
//   id: string;
//   title: string;
// }

// export interface State {
//   todos: Todo[];
// }

// export const initialState: State = {
//   todos: [],
// };

// export const reducer = createReducer(
//   initialState,
//   on(addTodo, (state: State, action: any) => ({
//     ...state,
//     todos: [
//       ...state.todos,
//       {
//         id: uuidv4(),
//         title: action.title,
//       },
//     ],
//   })),
//   on(delTodo, (state, action) => {
//     const newState: State = JSON.parse(JSON.stringify(state));
//     const index = newState.todos.findIndex((todo) => todo.id === action.id);
//     newState.todos.splice(index, 1);
//     return newState;
//   })
// );

import { Action, createReducer, on } from "@ngrx/store";
import { v4 as uuidv4 } from "uuid";
import { addTodo, delTodo } from "../actions/todo.actions";
import { EntityState, EntityAdapter, createEntityAdapter } from "@ngrx/entity";

export const todoFeatureKey = "todo";

export interface Todo {
  id: string;
  title: string;
}

export interface State extends EntityState<Todo> {}
export const adapter: EntityAdapter<Todo> = createEntityAdapter<Todo>();

export const initialState: State = adapter.getInitialState();

export const reducer = createReducer(
  initialState,
  on(addTodo, (state, action) =>
    adapter.addOne({ id: uuidv4(), title: action.title }, state)
  ),
  on(delTodo, (state, action) => adapter.removeOne(action.id, state))
);
